/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== "string") {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};

/**
 * 获取localStorage
 */
export const getStore = (name) => {
  if (!name) return;
  return window.localStorage.getItem(name);
};

/**
 * 删除localStorage
 */
export const removeStore = (name) => {
  if (!name) return;
  window.localStorage.removeItem(name);
};

/**
 * 函数防抖--不立即执行
 */
export const debounce = (fn, delay) => {
  // 记录上一次的延时器
  let timer = null;
  let delay1 = delay || 200;
  return function () {
    var args = arguments;
    var that = this;
    // 清除上一次延时器
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(that, args);
    }, delay1);
  };
};

/**
 * 函数防抖--立即执行
 */
export const debounce2 = (func, wait, immediate) => {
  let timer;
  return function () {
    let context = this;
    let args = arguments;
    if (timer) clearTimeout(timer);
    if (immediate) {
      var callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, wait);
      if (callNow) func.apply(context, args);
    } else {
      timer = setTimeout(function () {
        func.apply(context, args);
      }, wait);
    }
  };
};

/**
 * 防抖函数，返回函数连续调用时，空闲时间必须大于或等于 wait，func 才会执行
 *
 * @param  {function} func        回调函数
 * @param  {number}   wait        表示时间窗口的间隔
 * @param  {boolean}  immediate   设置为ture时，是否立即调用函数
 * @return {function}             返回客户调用函数
 */
export function deBounce(func, wait = 50, immediate = true) {
  let timer, context, args;

  // 延迟执行函数
  const later = () =>
    setTimeout(() => {
      // 延迟函数执行完毕，清空缓存的定时器序号
      timer = null;
      // 延迟执行的情况下，函数会在延迟函数中执行
      // 使用到之前缓存的参数和上下文
      if (!immediate) {
        func.apply(context, args);
        context = args = null;
      }
    }, wait);

  // 这里返回的函数是每次实际调用的函数
  return function (...params) {
    // 如果没有创建延迟执行函数（later），就创建一个
    if (!timer) {
      timer = later();
      // 如果是立即执行，调用函数
      // 否则缓存参数和调用上下文
      if (immediate) {
        func.apply(this, params);
      } else {
        context = this;
        args = params;
      }
      // 如果已有延迟执行函数（later），调用的时候清除原来的并重新设定一个
      // 这样做延迟函数会重新计时
    } else {
      clearTimeout(timer);
      timer = later();
    }
  };
}

/**
 * 函数节流
 */
export const throttle = (fn, delay) => {
  var lastTime;
  var timer;
  let delay1 = delay || 200;
  return function () {
    var args = arguments;
    // 记录当前函数触发的时间
    var nowTime = Date.now();
    if (lastTime && nowTime - lastTime < delay1) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        // 记录上一次函数触发的时间
        lastTime = nowTime;
        // 修正this指向问题
        fn.apply(this, args);
      }, delay1);
    } else {
      lastTime = nowTime;
      fn.apply(this, args);
    }
  };
};

/*
 * 日期格式化
 * 使用方式：
 *  let date = new Date()
 *  dateFormat("YYYY-mm-dd HH:MM:SS", date)
 *  2019-06-06 19:45:11
 *  let date1 = new Date()
 *  dateFormat("YYYY/mm/dd HH:MM", date1)
 *  2019/11/08 16:41
 */
export const dateFormat = (fmt, date) => {
  let ret;
  let opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString(), // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      );
    }
  }
  return fmt;
};

/*
 * 时间戳转化为日期格式
 * 参数一：时间戳
 * 参数二：分隔符 如'/','-'
 * timeStampTurnTime(new Date().getTime()/1000)
 * 2019-11-08 16:52:42
 * timeStampTurnTime(new Date().getTime()/1000,'/')
 * 2019/11/08 16:52:42
 */
export const timeStampTurnTime = (timeStamp, fmt = "-") => {
  if (timeStamp > 0) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = date.getDate();
    d = d < 10 ? "0" + d : d;
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    return y + fmt + m + fmt + d + " " + h + ":" + minute + ":" + second;
  }
};

/**
 * @description: 深拷贝
 * @param {type}
 * @return:
 * @author: 王强
 */
export function deepClone(obj) {
  let copy = obj instanceof Array ? [] : {};
  for (let i in obj) {
    if (obj.hasOwnProperty(i)) {
      copy[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
    }
  }
  return copy;
}

/**
 * @param {*} data   [后台数据]
 * @param {*} key    [要合并的字段]
 * @param {*} target [后台数据对应的index]
 * @returns 获取合并的行数
 */
export const getRowSpanCount = (data, key, target) => {
  if (!Array.isArray(data)) return 1;
  data = data.map((_) => _[key]); // 只取出筛选项
  let preValue = data[0];
  const res = [[preValue]]; // 放进二维数组里
  let index = 0; // 二维数组下标
  for (let i = 1; i < data.length; i++) {
    if (data[i] === preValue) {
      // 相同放进二维数组
      res[index].push(data[i]);
    } else {
      // 不相同二维数组下标后移
      index += 1;
      res[index] = [];
      res[index].push(data[i]);
      preValue = data[i];
    }
  }
  const arr = [];
  res.forEach((_) => {
    const len = _.length;
    for (let i = 0; i < len; i++) {
      arr.push(i === 0 ? len : 0);
    }
  });
  return arr[target];
};

/**
 * @param {*} datasource  表格数据   Array
 * @param {*} key    当前合并字段key
 * @param {*} index  当前数据行的索引值
 * @param {*} value   值
 * @param {*} firstKey   表格每行的第一个展示的字段
 */
export const getRowSpanCount2 = (datasource, key, index, value, firstKey) => {
  if (!Array.isArray(datasource)) return 1;
  let datas = datasource.map((_) => _[firstKey]); //第一字段数组集合
  let arrKey = datasource.map((_) => _[key]); //需要排序字段的数组集合
  let preValue = datas[0];
  const res = [[preValue]]; // 放进二维数组里
  let idx = 0; // 二维数组下标
  //1.第一个字段进行相同给的合并，组成二维数组
  for (let i = 1; i < datas.length; i++) {
    if (datas[i] === preValue) {
      // 相同放进二维数组
      res[idx].push(datas[i]);
    } else {
      // 不相同二维数组下标后移
      idx += 1;
      res[idx] = [];
      res[idx].push(datas[i]);
      preValue = datas[i];
    }
  }
  //2.根据上一步对需要排序的数据组成二维数组
  let sortArry = [];
  res.forEach((item, ind) => {
    sortArry[ind] = [];
    sortArry[ind] = arrKey.splice(0, item.length);
  });

  //3.根据二维数组组装三维数组，根据第一个字段分组的结果对需要分组的数据进行相同的合并
  let newArr = [];
  sortArry.forEach((item, ind) => {
    let first = sortArry[ind][0];
    let index = 0;
    newArr[ind] = [];
    newArr[ind][index] = [];
    item.forEach((list, i) => {
      if (first === list) {
        newArr[ind][index].push(list);
      } else {
        index += 1;
        newArr[ind][index] = [];
        newArr[ind][index].push(list);
        first = list;
      }
    });
  });

  //4.三维数组转换处理成二维数组
  let getArry = [];
  newArr.forEach((list) => {
    list.forEach((i) => {
      getArry.push(i);
    });
  });

  //5.根据二维数组计算出rowSpan的占位
  let arrs = [];
  getArry.forEach((item) => {
    const len = item.length;
    for (let i = 0; i < len; i++) {
      arrs.push(i === 0 ? len : 0);
    }
  });

  //6.赋值每一行的rowSpan
  const obj = {
    children: value,
    props: {},
  };
  obj.props.rowSpan = arrs[index];
  return obj;
};

// 动态加载 css js 文件
export function LoadJsCssFile(filename, filetype) {
  if (filetype == "js") {
    //如果是.js文件
    var fileref = document.createElement("script");
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filename);
  } else if (filetype == "css") {
    //如果是.css文件
    var fileref = document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", filename);
  }
  if (typeof fileref !== "undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

/**
 * 加载 script 文件
 * @param src
 */
function loadScript(src) {
  var addSign = true;
  var scripts = document.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i] && scripts[i].src && scripts[i].src.indexOf(src) != -1) {
      addSign = false;
    }
  }
  if (addSign) {
    var $script = document.createElement("script");
    $script.setAttribute("type", "text/javascript");
    $script.setAttribute("src", src);
    document.getElementsByTagName("head").item(0).appendChild($script);
  }
}

/**
 * 加载 link 文件
 * @param href
 */
function loadCss(href) {
  var addSign = true;
  var links = document.getElementsByTagName("link");
  for (var i = 0; i < links.length; i++) {
    if (links[i] && links[i].href && links[i].href.indexOf(href) !== -1) {
      addSign = false;
    }
  }
  if (addSign) {
    var $link = document.createElement("link");
    $link.setAttribute("rel", "stylesheet");
    $link.setAttribute("type", "text/css");
    $link.setAttribute("href", href);
    document.getElementsByTagName("head").item(0).appendChild($link);
  }
}

/**
 * 删除 script 文件
 * @param src
 */
function removeScript(src) {
  var scripts = document.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i] && scripts[i].src && scripts[i].src.indexOf(src) !== -1) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }
  }
}

/**
 * 删除 link 文件
 * @param href
 */
function removeCss(href) {
  var links = document.getElementsByTagName("link");
  for (var i = 0; i < links.length; i++) {
    var _href = links[i].href;
    if (links[i] && links[i].href && links[i].href.indexOf(href) !== -1) {
      links[i].parentNode.removeChild(links[i]);
    }
  }
}

// js 根据json数组中多个字段排序
/**
  data: [{
        name: '李寻欢',
        age: 32,
        rank: 1
    },
    {
        name: '谢晓峰',
        age: 28,
        rank: 4
    },
    {
        name: '潇十一郎',
        age: 27,
        rank: 5
    },
    {
        name: '楚留香',
        age: 29,
        rank: 3
    },
    {
        name: '傅红雪',
        age: 35,
        rank: 2
    }
]
  先根据rank排序，再根据age排序，最后根据name排序
   data.sort(compare('rank', compare('age', compare('name'))));
 */
export function compare(name, minor) {
  return function (o, p) {
    var a, b;
    if (o && p && typeof o === "object" && typeof p === "object") {
      a = o[name];
      b = p[name];
      if (a === b) {
        return typeof minor === "function" ? minor(o, p) : 0;
      }
      if (typeof a === typeof b) {
        return a < b ? -1 : 1;
      }
      return typeof a < typeof b ? -1 : 1;
    } else {
      throw "error";
    }
  };
}

const mockData = [
  {
    col_0: "粗抛槽",
    col_1: "初配",
    col_2: "时间",
    value: "9999",
    unit: "",
    id: "粗抛槽初配时间--0",
  },
  {
    col_0: "粗抛槽",
    col_1: "补液",
    col_2: "CDI",
    value: "1000",
    unit: "",
    id: "粗抛槽补液CDI--1",
  },
  {
    col_0: "粗抛槽",
    col_1: "初配",
    col_2: "温度",
    value: "80",
    unit: "",
    id: "粗抛槽初配温度--2",
  },
  {
    col_0: "粗抛槽",
    col_1: "补液",
    col_2: "HDI",
    value: "9000",
    unit: "",
    id: "粗抛槽补液HDI--3",
  },
  {
    col_0: "粗抛槽",
    col_1: "补液",
    col_2: "KOH",
    value: "800",
    unit: "",
    id: "粗抛槽补液KOH--4",
  },
  {
    col_0: "粗抛槽",
    col_1: "初配",
    col_2: "KOH",
    value: "40000",
    unit: "",
    id: "粗抛槽初配KOH--5",
  },
  {
    col_0: "预清洗槽",
    col_1: "初配",
    col_2: "温度",
    value: "70",
    unit: "",
    id: "预清洗槽初配温度--6",
  },
  {
    col_0: "制绒槽1",
    col_1: "初配",
    col_2: "温度",
    value: "82",
    unit: "",
    id: "制绒槽1初配温度--7",
  },
  {
    col_0: "制绒槽2",
    col_1: "初配",
    col_2: "温度",
    value: "82",
    unit: "",
    id: "制绒槽2初配温度--8",
  },
  {
    col_0: "制绒槽3",
    col_1: "初配",
    col_2: "温度",
    value: "82",
    unit: "",
    id: "制绒槽3初配温度--9",
  },
  {
    col_0: "慢提拉槽",
    col_1: "",
    col_2: "温度",
    value: "70",
    unit: "",
    id: "慢提拉槽温度--10",
  },
  {
    col_0: "风干槽1",
    col_1: "",
    col_2: "温度",
    value: "90",
    unit: "",
    id: "风干槽1温度--11",
  },
  {
    col_0: "风干槽2",
    col_1: "",
    col_2: "温度",
    value: "90",
    unit: "",
    id: "风干槽2温度--12",
  },
  {
    col_0: "风干槽3",
    col_1: "",
    col_2: "温度",
    value: "90",
    unit: "",
    id: "风干槽3温度--13",
  },
  {
    col_0: "风干槽4",
    col_1: "",
    col_2: "温度",
    value: "90",
    unit: "",
    id: "风干槽4温度--14",
  },
  {
    col_0: "预清洗槽",
    col_1: "初配",
    col_2: "时间",
    value: "135",
    unit: "",
    id: "预清洗槽初配时间--15",
  },
  {
    col_0: "制绒槽1",
    col_1: "初配",
    col_2: "时间",
    value: "430",
    unit: "",
    id: "制绒槽1初配时间--16",
  },
  {
    col_0: "制绒槽2",
    col_1: "初配",
    col_2: "时间",
    value: "430",
    unit: "",
    id: "制绒槽2初配时间--17",
  },
  {
    col_0: "制绒槽3",
    col_1: "初配",
    col_2: "时间",
    value: "430",
    unit: "",
    id: "制绒槽3初配时间--18",
  },
  {
    col_0: "臭氧槽",
    col_1: "初配",
    col_2: "时间",
    value: "120",
    unit: "",
    id: "臭氧槽初配时间--19",
  },
  {
    col_0: "酸洗1槽",
    col_1: "初配",
    col_2: "时间",
    value: "",
    unit: "",
    id: "酸洗1槽初配时间--20",
  },
  {
    col_0: "酸洗1槽",
    col_1: "初配",
    col_2: "时间",
    value: "",
    unit: "",
    id: "酸洗1槽初配时间--21",
  },
  {
    col_0: "慢提拉槽",
    col_1: "",
    col_2: "时间",
    value: "10",
    unit: "",
    id: "慢提拉槽时间--22",
  },
  {
    col_0: "风干槽1",
    col_1: "",
    col_2: "时间",
    value: "560",
    unit: "",
    id: "风干槽1时间--23",
  },
  {
    col_0: "风干槽2",
    col_1: "",
    col_2: "时间",
    value: "560",
    unit: "",
    id: "风干槽2时间--24",
  },
  {
    col_0: "风干槽3",
    col_1: "",
    col_2: "时间",
    value: "560",
    unit: "",
    id: "风干槽3时间--25",
  },
  {
    col_0: "风干槽4",
    col_1: "",
    col_2: "时间",
    value: "560",
    unit: "",
    id: "风干槽4时间--26",
  },
  {
    col_0: "预清洗槽",
    col_1: "补液",
    col_2: "CDI",
    value: "1000",
    unit: "",
    id: "预清洗槽补液CDI--27",
  },
  {
    col_0: "预清洗槽",
    col_1: "补液",
    col_2: "H2O2",
    value: "500",
    unit: "",
    id: "预清洗槽补液H2O2--28",
  },
  {
    col_0: "预清洗槽",
    col_1: "补液",
    col_2: "HDI",
    value: "2000",
    unit: "",
    id: "预清洗槽补液HDI--29",
  },
  {
    col_0: "预清洗槽",
    col_1: "补液",
    col_2: "KOH",
    value: "90",
    unit: "",
    id: "预清洗槽补液KOH--30",
  },
  {
    col_0: "制绒槽1",
    col_1: "补液",
    col_2: "ADDI",
    value: "200",
    unit: "",
    id: "制绒槽1补液ADDI--31",
  },
  {
    col_0: "制绒槽1",
    col_1: "补液",
    col_2: "HDI",
    value: "10000",
    unit: "",
    id: "制绒槽1补液HDI--32",
  },
];

// mockData.sort(compare("col_0", compare("col_1")));
// export { mockData };

/**数组根据数组对象中的某个属性值进行排序的方法
 * 使用例子：newArray.sort(sortByArr(['number'],false)) //表示根据number属性降序排列;若第二个参数不传递，默认表示升序排序
 * @param attr 排序的属性 ['name','sex'],根据一个字段或者多个字段排序
 * @param rev true表示升序排列，false降序排序
 * */
export function sortByArr(arr, rev) {
  if (rev == undefined) {
    rev = 1;
  } else {
    rev = rev ? 1 : -1;
  }
  return function (a, b) {
    for (var i = 0; i < arr.length; i++) {
      let attr = arr[i];
      if (a[attr] != b[attr]) {
        if (a[attr] > b[attr]) {
          return rev * 1;
        } else {
          return rev * -1;
        }
      }
    }
  };
}

mockData.sort(sortByArr(['col_0', 'col_1']))
export { mockData };